<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/9/14 13:57
 */

namespace module\user\front\input;

use app\library\validate\UploadImageValidate;
use mof\exception\LogicException;
use mof\Request;
use think\Image;

class AvatarInput
{
    public function __construct(protected array $data)
    {
    }

    public static function __make(Request $request): static
    {
        list($rules, $messages) = upload_validate_rules('image', ['require']);

        $data = [];
        $data['file'] = $request->file('file');
        $request->withValidate(['file' => $rules], $messages)->validate($data);

        return new self($data);
    }

    public function __get($name)
    {
        return $this->data[$name] ?? null;
    }

    public function data(): array
    {
        return $this->data;
    }

    public function saveToStorage(): string
    {
        $file = $this->data['file'];

        if (!$image = Image::open($file)) {
            throw new LogicException('图片读取失败');
        }
        //限制图片尺寸
        $maxW = 500;
        $maxH = 500;
        //图片过大，进行所小
        $image->thumb($maxW, $maxH)->save($file->getRealPath());

        //保存
        try {
            $dir = 'avatars'; //头像目录
            $fs = app('filesystem')->disk();
            $path = $fs->putFile($dir, $file);    //保存文件
            if (!$path) {
                throw new LogicException('图片保存失败');
            }
            return $path;
        } catch (\Exception $e) {
            throw new LogicException('图片保存出错(' . $e->getMessage() . ')');
        }
    }
}